const db = require("../config/mysql_util");
class OrdersModel {
  constructor() {}
  getCount(data) {
    let sql = `select count(*) count from orders o 
      inner join users u on o.user_id = u.user_id where 1 `;
    if (data.order_no) sql += ` and order_no like '%${data.order_no}%' `;
    if (data.user_name) sql += ` and user_name like '%${data.user_name}%' `;
    if (data.status) sql += ` and status like '%${data.status}%' `;
    if (data.sjr) sql += ` and sjr like '%${data.sjr}%' `;
    if (data.sjdz) sql += ` and sjdz like '%${data.sjdz}%' `;
    if (data.tel) sql += ` and tel like '%${data.tel}%' `;
    if (data.user_id) sql += ` and o.user_id = ${data.user_id} `;
    return db.query(sql);
  }

  getAll(data) {
    let limit = data.pagesize * (data.page - 1);
    let sql = ` select o.*, u.user_name, u.user_id from orders o 
      inner join users u on o.user_id = u.user_id  where 1 `;
    if (data.order_no) sql += ` and order_no like '%${data.order_no}%' `;
    if (data.user_name) sql += ` and user_name like '%${data.user_name}%' `;
    if (data.status) sql += ` and status like '%${data.status}%' `;
    if (data.sjr) sql += ` and sjr like '%${data.sjr}%' `;
    if (data.sjdz) sql += ` and sjdz like '%${data.sjdz}%' `;
    if (data.tel) sql += ` and tel like '%${data.tel}%' `;
    if (data.user_id) sql += ` and o.user_id = ${data.user_id} `;
    sql += ` order by order_id desc limit ${limit}, ${data.pagesize} `;
    return db.query(sql);
  }

  update(data, order_id) {
    return db.query("update orders set ? where order_id = ?", [data, order_id]);
  }

  queryDetail(order_id, user_id){
    let sql = ` select od.*,goods_name, goods_price, goods_big_logo, goods_small_logo, user_id from orders_detail od 
      inner join orders o on o.order_id = od.order_id
      inner join goods g on g.goods_id = od.goods_id
      where 1 `
    if(order_id) sql += ` and od.order_id = ${order_id} `
    if(user_id) sql += ` and user_id = ${user_id} `
    return db.query(sql);
  }

  insert(data) {
    return db.query("insert into orders set ?", [data]);
  }

  insertDetail(data){
    return db.query("insert into orders_detail set ?", [data]);
  }
}

module.exports = new OrdersModel();